# -*- coding: utf-8 -*-

try:
    import xml.etree.ElementTree as ET
except:
    import cElementTree as ET # for 2.4

from object_dict import object_dict 
from object_dict import ObjectDict 
import re
import types
import ShareFunc as SF

class XMLSDT:
    @staticmethod
    def replaceXmlEncoding(xmstr=None,charset="utf-8"):
        return SF.ShareFunc.replaceXmlEncoding(xmstr, charset)
            
class XML2Dict(object):

    def __parseNode(self, node):
        nodeTree = object_dict()
        lastTag = None
        if self.filter:
            result = re.compile("^\S").search(unicode(node.text))
        else:
            result = True
        if result:
            nodeTree.value = node.text

        for (k,v) in node.attrib.items():
            k,v = self.__namespaceSplit(k, object_dict({'value':v}))
            nodeTree[k] = v
            
        for child in node:
            tag, tree = self.__namespaceSplit(child.tag, self.__parseNode(child))
            if  tag not in nodeTree:
                if (isinstance(nodeTree, (type,types.DictType))):
                    nodeTree[tag] = tree                    
                elif (isinstance(nodeTree, (type,types.ListType))):
                    nodeTree.append({tag:tree})
                lastTag = tag
                continue
            if lastTag == tag:
                old = nodeTree[tag]
                if not (isinstance(old, (type,types.ListType))):
                    nodeTree.pop(tag)
                    nodeTree[tag] = [old]
                nodeTree[tag].append(tree)
            else:
                newTreeList = []
                transform = False
                for l in nodeTree.keys():
                    newTreeList.append({l:nodeTree[l]})
                newTreeList.append({tag:tree})
                nodeTree.pop(tag)
                nodeTree = newTreeList

        return  nodeTree

    def __namespaceSplit(self, tag, value):
        result = re.compile("\{(.*)\}(.*)").search(tag) 
        if result:
            value.namespace, tag = result.groups()
        return (tag, value)

    def parse(self, file):
        f = open(file, 'r')
        return self.fromString(f.read()) 

    def fromString(self, s, result=True):
        self.filter = result
        t = ET.fromstring(s)

        root_tag, root_tree = self.__namespaceSplit(t.tag, self.__parseNode(t))
        return object_dict({root_tag: root_tree})

class XML2DictEx(object):

    def __parseNode(self, node):
        nodeTree = ObjectDict()
        lastTag = None
        if self.filter:
            result = re.compile("^\S+$").search(unicode(node.text))
        else:
            result = True
        if result:
            nodeTree.value = node.text

        for (k,v) in node.attrib.items():
            k,v = self.__namespaceSplit(k, ObjectDict({'value':v}))
            nodeTree[k] = v
            
        for child in node:
            tag, tree = self.__namespaceSplit(child.tag, self.__parseNode(child))
            if  tag not in nodeTree:
                if (isinstance(nodeTree, (type,types.DictType))):
                    nodeTree[tag] = tree                    
                elif (isinstance(nodeTree, (type,types.ListType))):
                    nodeTree.append({tag:tree})
                lastTag = tag
                continue
            if lastTag == tag:
                old = nodeTree[tag]
                if not (isinstance(old, (type,types.ListType))):
                    nodeTree.pop(tag)
                    nodeTree[tag] = [old]
                nodeTree[tag].append(tree)
            else:
                newTreeList = []
                transform = False
                for l in nodeTree.keys():
                    newTreeList.append({l:nodeTree[l]})
                newTreeList.append({tag:tree})
                nodeTree.pop(tag)
                nodeTree = newTreeList

        return  nodeTree

    def __namespaceSplit(self, tag, value):
        result = re.compile("\{(.*)\}(.*)").search(tag) 
        if result:
            value.namespace, tag = result.groups()
        return (tag, value)

    def parse(self, file):
        f = open(file, 'r')
        return self.fromString(f.read()) 

    def fromString(self, s, result=True):
        self.filter = result
        t = ET.fromstring(s)

        root_tag, root_tree = self.__namespaceSplit(t.tag, self.__parseNode(t))
        return ObjectDict({root_tag: root_tree})
    


if __name__ == '__main__':
    import sys
    s = """<?xml version="1.0" encoding="gbk" ?>
    <suite name="add_dns_alias">
        <setUp>haha
            <step>为真</step>
        </setUp>
    </suite>"""
    
    s1 = """<?xml version="1.0" encoding="utf-8" ?>
<sdtest>
    <log>
        <result>/home/admin/zengyixun/SDTest/log/result.log</result>
        <detail>/home/admin/zengyixun/SDTest/log/detail.log</detail>
    </log>
    <module name="Cupid">
        <datafile></datafile>
    </module>
    <module name="CupidDemo">
        <datafile>haha</datafile>
    </module>
</sdtest>"""
    s3 = '''
    <conditions><condition queryType=\"25123\">
    <item><name>subreportIDswww</name><value>95333011</value></item>
    <item><name>subreportIDs</name><value>95011</value></item><item><name>corpName</name><value>阿里巴巴(中国)网络技术有限公司</value></item></condition></conditions>'''
    
    s4 = '''<conditions><condition queryType="25136"><item><name>name</name><value>曾一迅</value></item><item><name>documentNo</name><value>313039834737437</value></item><item><name>subreportIDs</name><value>96002</value></item></condition></conditions>'''
    gonganCondition = '''<?xml version="1.0" encoding="UTF-8"?><ROWS><INFO><SBM>XXXXXX</SBM></INFO><ROW><GMSFHM>公民身份号码</GMSFHM><XM>姓名</XM></ROW><ROW FSD="XXXXXX" YWLX="XXXXXX"><GMSFHM>XXXXXX</GMSFHM><XM>XXXXXX</XM></ROW><ROW FSD="XXXXXX" YWLX="XXXXXX"><GMSFHM>XXXXXX</GMSFHM><XM>XXXXXX</XM></ROW></ROWS>'''
    gonganCondition = gonganCondition.decode(sys.stdin.encoding).encode(sys.stdin.encoding)

#     file = open("./testabc.xml",'r')
#     xmlString = ''.join(file.readlines())    
    xml = XML2Dict()
    #s1 = SF.ShareFunc.replaceXmlEncoding(s1)
    r = xml.fromString(gonganCondition)
    print r.ROWS.ROW[1].GMSFHM
    print r.ROWS.ROW[1].XM
    print type(r.ROWS.ROW)
    
#     queryType = 25123
#     FindName = None
#     companyName = None
#     orgCode = None
#     registerNo =None
#     subreportIDs = 95011
#     personName = None
#     #documentNo，个人的身份证号
#     documentNo = None
#     for item in items:
#         if type(item) is dict:
#             if item.has_key("name"):
#                 FindName = item["name"]["value"].strip()
#             if item.has_key("value") and (FindName=="name"):
#                 personName = item["value"]["value"]
#                 FindName = None
#             if item.has_key("value") and (FindName=="documentNo"):
#                 documentNo = item["value"]["value"]
#                 FindName = None
#             if item.has_key("value") and (FindName=="corpName"):
#                 companyName = item["value"]["value"]
#                 FindName = None
#             if item.has_key("value") and (FindName=="subreportIDs"):
#                 subreportIDs = item["value"]["value"]
#                 FindName = None
#             if item.has_key("value") and (FindName=="registerNo"):
#                 registerNo = item["value"]["value"]
#                 FindName = None
#             if item.has_key("value") and (FindName=="orgCode"):
#                 orgCode = item["value"]["value"]
#                 FindName = None
#             if item.has_key("value"):
#                 print item["value"]
#         if type(item) is list:
#             for t in item:
#                 if type(t) is not dict:
#                     continue
#                 if t.has_key("name"):
#                     FindName = t["name"]["value"].strip()
#                 if t.has_key("value") and (FindName=="name"):
#                     personName = t["value"]["value"]
#                     FindName = None
#                 if t.has_key("value") and (FindName=="documentNo"):
#                     print t["value"]
#                     documentNo = t["value"]["value"]
#                     FindName = None
#                 if t.has_key("value") and (FindName=="corpName"):
#                     companyName = t["value"]["value"]
#                     FindName = None
#                 if t.has_key("value") and (FindName=="subreportIDs"):
#                     subreportIDs = t["value"]["value"]
#                     FindName = None
#                 if t.has_key("value") and (FindName=="registerNo"):
#                     registerNo = t["value"]["value"]
#                     FindName = None
#                 if t.has_key("value") and (FindName=="orgCode"):
#                     orgCode = t["value"]["value"]
#                     FindName = None
#                 if t.has_key("value"):
#                     print t["value"]
    
    
    
    
    